/**
 * Copyright (c) 2015, 漆夜
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without modification,
 * are permitted provided that the following conditions are met:
 *
 * * Redistributions of source code must retain the above copyright notice, this
 *   list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright notice, this
 *   list of conditions and the following disclaimer in the documentation and/or
 *   other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
 * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

#ifndef MUTEX_H
#define MUTEX_H

#include <pthread.h>

namespace redis { namespace helper {

/**
 * @brief The NoneMutex class 空锁
 */
class NoneMutex
{
public:
    NoneMutex() {}
    ~NoneMutex() {}

    void lock() {}
    bool try_lock() { return true;}
    void unlock() {}

protected:

};

/**
 * @param T传入所的类型
 */
template <int T>
class PthreadMutex : public NoneMutex
{
public:
    PthreadMutex()
    {
        pthread_mutexattr_init(&m_pthr_mutex_attr);
        pthread_mutexattr_settype(&m_pthr_mutex_attr, m_mutex_type);
        pthread_mutex_init(&m_pthr_mutex, &m_pthr_mutex_attr);
    }

    ~PthreadMutex()
    {
        pthread_mutex_destroy(&m_pthr_mutex);
    }

    void lock()
    {
         pthread_mutex_lock(&m_pthr_mutex);
    }

    bool try_lock()
    {
        return 0 == pthread_mutex_trylock(&m_pthr_mutex);
    }

    void unlock()
    {
        pthread_mutex_unlock(&m_pthr_mutex);
    }

protected:
    static const int m_mutex_type = T;
    pthread_mutex_t m_pthr_mutex;
    pthread_mutexattr_t m_pthr_mutex_attr;
};

/// @class 不可重入锁
typedef PthreadMutex<PTHREAD_MUTEX_NORMAL> ThreadMutex;
/// @class 可重入锁
typedef PthreadMutex<PTHREAD_MUTEX_RECURSIVE> RrecursiveMutex;

/**
 * @class Locker 自动加锁与解锁
 * @param MutexType 可重入和不可重入锁
 */
template<class MutexType>
class Locker
{
public:
    Locker(MutexType &mutex):
        m_mutex(mutex)
    {
        m_mutex.lock();
    }

    virtual ~Locker()
    {
        m_mutex.unlock();
    }

protected:
    MutexType &m_mutex;
};

}}

#endif // MUTEX_H
